# -*- coding: utf-8 -*-

from flask import g, session, request, abort, redirect, render_template
from . import config, create_login_url


def login_handler():
    """ """
    google_user = g.google_user
    
    if not google_user:
        return redirect(create_login_url(request.args.get('next') or config.DEFAULT_DESTINATION))
    
    return _login_handler(user_class= config.User,
                          google_user_openid= google_user.openid,
                          next= request.args.get('next') or config.DEFAULT_DESTINATION)
    

def create_user_handler():
    """ """
    google_user = g.google_user or abort(403)
    return _create_user_handler(name= request.form['name'], 
                                google_user_openid= google_user.openid,
                                next= request.form.get('next') or config.DEFAULT_DESTINATION,
                                validator= config.USER_NAME_VALIDATOR,
                                user_class= config.User,
                                user_errors= config.UserExceptions)
    
def logout_handler():
    """ """
    session.pop(config.SESSION_KEY_NAME, None)
    return redirect(request.args.get('next') or config.DEFAULT_DESTINATION)    

 
def _login_handler(user_class, google_user_openid, next):        
    """ """
    app_user = user_class.get_by_openid(google_user_openid)
    
    if app_user:
        # login user
        session[config.SESSION_KEY_NAME] = {
            'name': app_user.name,
            'openid': app_user.openid
        }
        return redirect(next)
    else:
        return render_template('auth/create_user.html', next=next)


def _create_user_handler(name, google_user_openid, next, validator, user_class, user_errors=None):
    """ """
    name_validated, error = validator(name)
    
    if name_validated:
        app_user = user_class.new(name_validated, google_user_openid)
        try:
            app_user.put()
        except Exception, e:
            if user_errors:
                try:
                    error = user_errors[type(e)]
                except KeyError:
                    raise e
            else:
                raise e    
        else:    
            session[config.SESSION_KEY_NAME] = {
                'name': app_user.name,
                'openid': app_user.openid
            }
            return redirect(next)
    return render_template('auth/create_user.html', name=name, error=error)        